import editForm from "../form.vue";
import { usePublicHooks } from "../../../hooks";
import { usePublicFormats } from "../../../formats";
import type { FormItemProps } from "./types"
import { addDialog } from "@/components/ReDialog";
import { reactive, onMounted, h, toRaw } from "vue";
import { delay } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { bannerList, addBanner, updateBanner, deleteBanner } from "@/api/dingtalk/banner";

export function staticConfig() {
  const form = reactive({
    class_id: -1,
    page: 1,
    limit: 20
  });

  //从父级钩子里取东西
  const { tagStyle, pagination, loadingConfig, formRef, dataList, loading } =
    usePublicHooks();

  const { paymentMethodShow } = usePublicFormats();

  const columns: TableColumnList = [
    {
      label: "id",
      prop: "id",
      width: 100
    },
    {
      label: "位置",
      prop: "class_id",
      cellRenderer: ({ row }) => {
        let class_id_return: string;
        switch (row.class_id) {
          case 1:
            class_id_return = "banner";
            break;
          case 2:
            class_id_return = "首页广告位";
            break;
        }
        return h(
          "span",
          { style: { class_id_return } },
          class_id_return
        );
      },
    },
    {
      label: "banner",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.image_path}
          preview-src-list={Array.of(row.image_path)}
          class="w-[48px] h-[48px] "
        />
      ),
    },
    {
      label: "排序",
      prop: "sort",
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const { data } = await bannerList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function openDialog(title = "修改", row?: FormItemProps) {
    console.log("row:", row);
    addDialog({
      title: `${title}banner`,
      props: {
        formInline: {
          id: row?.id ?? "",
          sort: row?.sort ?? "",
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了ID为${curData.id}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "修改") {
              updateBanner(curData).then(() => {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              });
            } else {
              addBanner(curData).then(() => {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              });
            }
          }
        });
      }
    });
  }

  //页面加载
  onMounted(() => {
    onSearch();
  });

  //页面条数变化
  function onSizeChange(val) {
    form.limit = val;
    onSearch();
  }

  //页码变化
  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      form.page = val;
      onSearch();

      //刷新数据
      loading.value = false;
    });
  }

  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function handleDelete(row) {
    deleteBanner(row).then((res) => {
      if (res.success) {
        message(`您删除了菜单名称为${row.title}的这条数据`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  return {
    columns,
    openDialog,
    form,
    loading,
    onSearch,
    resetForm,
    dataList,
    pagination,
    onSizeChange,
    onCurrentChange,
    loadingConfig,
    handleDelete
  };
}
